<!-- 系统内容编辑页面 -->
<template>
  <div class="system-content-item" v-loading="globalLoading">
    <!-- <div class="header">
      <el-row type="flex" justify="end">
        <el-button type="warning" size="small" v-if="system && system.systemType && system.systemType.id === 1"
          @click="categoryTreeShow">分类级别树形结构</el-button>
        <el-button type="warning" size="small" v-if="system && system.systemType && system.systemType.id === 2"
          @click="slugTreeShow">短标题级别树形结构</el-button>
        <el-button type="primary" @click="onSubmit" size="small">保存</el-button>
        <el-button type="success" @click="onSubmitAndGoSystemList" size="small">保存并返回系统列表</el-button>
        <el-button size="small" @click="goSystemList">返回系统列表</el-button>
      </el-row>
      <div class="border"></div>
    </div> -->
    <el-form ref="articleForm" :model="article" label-width="130px" :rules="rules" v-loading="formLoading">
      <SystemArticleItemForm ref="systemArticleItemForm" :categories="categories" :sluges="sluges" :system="system"
        :article="article" :globalLoading="globalLoading"
        :resetImageList="resetImageList"
        :contentChange="contentChange" :categoryTreeShow="categoryTreeShow" :slugTreeShow="slugTreeShow" :isSetUecontent="isSetUecontent" :resetFileList="resetFileList"/>
      <el-form-item class="footfixed">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button type="success" @click="onSubmitAndGoSystemList">保存并返回系统列表</el-button>
        <el-button @click="goSystemList">返回系统列表</el-button>
      </el-form-item>
    </el-form>
    <!-- 分类级别树形结构显示 -->
    <TreeDialog :data="categoryTreeDialog" ref="categoryTreeDialog" title="分类级别树形结构显示" />
    <!-- 短标题级别树形结构显示 -->
    <TreeDialog :data="slugTreeDialog" ref="slugTreeDialog" title="短标题级别树形结构显示" />
  </div>
</template>

<script>
import SystemArticleItemForm from '@/components/main/user/system/article/item/SystemArticleItemForm.vue'
import TreeDialog from '@/components/common/dialog/TreeDialog.vue'
import * as functions from '@/core/functions.js'
export default {
  created () {
    let query = this.$route.query
    if (!query || !query.sid || !query.id) {
      this.$message.error('未能获取到正确的数据')
      return
    }
    let systemId = query.sid
    let id = query.id
    let hRepertoryId
    if (query.hrepertoryId) {
      hRepertoryId = query.hrepertoryId
    }
    // 获取系统信息
    this.$post('/system/info', { id: systemId }).then((resoponse) => {
      if (resoponse && resoponse.id) {
        this.system = resoponse
        this.article.systemId = this.system.id
        if (this.system.systemType && this.system.systemType.id === 1) {
          // 获取所有的分类信息
          this.$post('/category/table-data-infos-by-system-id', { systemId: systemId }).then((resoponse) => {
            if (resoponse.categories) {
              this.categories = resoponse.categories
            } else {
              this.categories = {}
            }
            if (resoponse.categoryIds && resoponse.categoryIds.length > 0) {
              this.article.categoryId = resoponse.categoryIds[0]
            }
            this.initComplete.categories = true
          })
        } else if (this.system.systemType && this.system.systemType.id === 2) {
          this.rules.slug.push({ required: true, message: '请输入短标题名称', trigger: 'blur' })
          this.rules.slug.push({ max: 200, message: '不得超过64个字符', trigger: 'blur' })
          // 获取所有的短标题信息
          this.$post('/system/article/slug-infos', { systemId: systemId }).then((resoponse) => {
            if (resoponse) {
              this.sluges = resoponse
            } else {
              this.sluges = {}
            }
            this.initComplete.categories = true
          })
        } else {
          // 不需要获取分类信息
          this.initComplete.categories = true
        }
      }
      this.initComplete.system = true
    })
    // 获取内容信息
    if (id > 0) {
      this.isSetUecontent = false
      // 修改
      this.$post('/system/article/info', { articleId: id }).then(response => {
        let article = response
        if (article) {
          this.article = initArticle(article, this)
          this.isSetUecontent = true
        }
        this.initComplete.data = true
      })
    } else {
      if (hRepertoryId) {
        this.isSetUecontent = false
        // word获取
        this.$post('/system/repertory-word-to-html', { hRepertoryId: hRepertoryId }).then(response => {
          if (response) {
            let title = ''
            if (response.title && response.title.lastIndexOf('.') !== -1) {
              title = response.title.substring(0, response.title.lastIndexOf('.'))
            } else if (response.title) {
              title = response.title
            }
            this.article.title = title
            this.article.content = response.content ? response.content : ''
            this.isSetUecontent = true
          }
        })
      }
      this.$post('/url/item-custom-link-path-one-group-by-system-id', {systemId: systemId}).then(response => {
        if (response && response.length > 0) {
          this.article.customLink.pathOneGroup = response
        }
      })
      // 新增
      this.initComplete.data = true
    }
  },
  data () {
    var checkViewCount = (rule, value, callback) => {
      if (value > 1000000000) {
        return callback(new Error('浏览量数字过大，设值不超过10亿！'))
      } else {
        callback()
      }
    }
    return {
      // 全局加载中
      globalLoading: true,
      // 表单加载
      formLoading: false,
      // 判断是否加载完成的三个加载项目
      initComplete: {
        categories: false,
        system: false,
        data: false
      },
      // 获取系统的分类信息
      categories: {},
      // 获取文章分级信息
      sluges: {},
      // 当前的系统
      system: {},
      // 当前content的数据
      data: {},
      // 表单数据
      article: {
        // 图片列表
        imageList: [],
        id: 0,
        categoryId: -1,
        systemId: 0,
        title: '',
        author: '',
        origin: '',
        synopsis: '',
        rewrite: '',
        orderNum: 1,
        isShow: 1,
        content: '',
        releasedAt: new Date(),
        // 短标题ID
        slugId: 0,
        // 短标题父级ID
        slugParentId: 0,
        // 短标题 title
        slug: '',
        // seo 信息
        seo: { id: 0, systemId: 0, title: '', keywords: '', description: '' },
        fileList: [],
        // 自定义链接信息
        customLink: { id: 0, systemId: 0, status: 1, path: [], lanno: '', pathOneGroup: [], suffix: '.html' }
      },
      // 提交的表单规则
      rules: {
        title: [
          { required: true, message: '请输入标题名称', trigger: 'blur' },
          { max: 200, message: '不得超过200个字符', trigger: 'blur' }
        ],
        viewCount: [
          { validator: checkViewCount, trigger: 'blur' }
        ],
        slug: []
      },
      // 是否显示短标题树形结构
      isShowSlugTreeDialog: true,
      isSetUecontent: false
    }
  },
  computed: {
    slugTreeDialog () {
      let result = getSlugTreeData(this.sluges, 0)
      return result
    },
    categoryTreeDialog () {
      let result = getCategoryTreeData(this.categories, 0)
      return result
    }
  },
  watch: {
    initComplete: {
      handler (newVal) {
        this.$nextTick(() => {
          if (newVal.categories && newVal.system && newVal.data) {
            // 初始化请求完毕
            this.globalLoading = false
          }
        })
      },
      deep: true
    }
  },
  methods: {
    // 保存
    onSubmit (callback) {
      this.$refs['articleForm'].validate((valid) => {
        if (valid) {
          this.article.content = this.$refs['systemArticleItemForm'].getContent()
          this.article.seoTitle = this.article.seo.title
          this.article.seoKeywords = this.article.seo.keywords
          this.article.seoDescription = this.article.seo.description
          let itemCustomLinkInfo = this.$refs['systemArticleItemForm'].getCustomLink()
          let itemCustomLink
          if (!itemCustomLinkInfo.bool) {
            return
          } else {
            itemCustomLink = {
              path: itemCustomLinkInfo.path,
              status: itemCustomLinkInfo.status
            }
          }
          this.article.itemCustomLink = itemCustomLink
          this.article = JSON.parse(JSON.stringify(this.article))
          this.formLoading = true
          this.$jpost('/system/article/save', this.article).then(response => {
            let article = response
            if (article) {
              if (typeof callback === 'function') {
                callback()
              }
              this.article = initArticle(article, this)
            } else {
              console.error(response)
            }
            this.formLoading = false
          })
        } else {
          console.log('error submit!!')
          this.$refs['systemArticleItemForm'].gotoFirst()
          return false
        }
      })
    },
    // 保存并返回系统列表
    onSubmitAndGoSystemList () {
      this.onSubmit(() => {
        this.goSystemList()
      })
    },
    // 返回系统列表
    goSystemList () {
      let fullPath = functions.getSystemListPathByItem(this.system)
      if (!fullPath) {
        return
      }

      // 存储系统页面页码，如果从编辑页返回列表页fromItem改为true
      let systbPageCur = JSON.parse(sessionStorage.getItem('systbPageCur' + this.system.id))
      if (systbPageCur) {
        systbPageCur.fromItem = true
        sessionStorage.setItem('systbPageCur' + this.system.id, JSON.stringify(systbPageCur))
      }

      this.$store.dispatch('navAppendAndClose', { path: fullPath, close: this.$route.fullPath })
    },
    // 当内容变化的时候
    contentChange (content) {
      this.article.content = content
    },
    // 重置当前的图片列表
    resetImageList (list) {
      this.article.imageList = list
    },
    // 点击显示分类树形结构弹窗
    categoryTreeShow () {
      this.$refs['categoryTreeDialog'].show()
    },
    // 点击显示短标题树形结构弹窗
    slugTreeShow () {
      this.$refs['slugTreeDialog'].show()
    },
    // 重新设置文件列表
    resetFileList (fileList) {
      this.article.fileList = fileList
    }
  },
  components: {
    SystemArticleItemForm,
    TreeDialog
  }
}

function getCategoryTreeData (data, key) {
  if (data.length < 1) {
    return []
  }
  let result = []
  for (let i in data[key]) {
    let item = data[key][i]
    let children
    if (data.hasOwnProperty(item.id)) {
      children = getCategoryTreeData(data, item.id)
    }
    let element = {}
    element.label = item.name
    if (children) {
      element.children = children
    }
    result.push(element)
  }
  return result
}

function getSlugTreeData (data, key) {
  if (data.length < 1) {
    return []
  }
  let result = []
  for (let i in data[key]) {
    let item = data[key][i]
    let children
    if (data.hasOwnProperty(item.id)) {
      children = getSlugTreeData(data, item.id)
    }
    let element = {}
    element.label = item.slug
    if (children) {
      element.children = children
    }
    result.push(element)
  }
  return result
}

function initArticle (article, vm) {
  let imageList = []
  if (article.repertoryQuote && article.repertoryQuote.srepertoryQuote && article.repertoryQuote.srepertoryQuote.id && article.repertoryQuote.hrepertory.id) {
    let item = article.repertoryQuote.hrepertory
    let quote = article.repertoryQuote.srepertoryQuote
    let config
    if (quote.config) {
      config = JSON.parse(quote.config)
    }
    let title = config && config.title ? config.title : item.originalFilename
    let alt = config && config.alt ? config.alt : item.originalFilename

    let repertoryImageSrc = { hostId: vm.$store.state.host.id, repertoryId: item.id, suffix: item.suffix, type: item.type, link: item.link }
    imageList.push({
      id: item.id,
      src: functions.getRepertoryImageSrc(repertoryImageSrc),
      title: title,
      alt: alt
    })
  }

  let categoryId = -1
  if (article.categoryQuote && article.categoryQuote.scategories) {
    categoryId = article.categoryQuote.scategories.id
  }

  let slugId = 0
  let slugParentId = 0
  let slug = ''
  if (article.sarticleSlug && article.sarticleSlug.id) {
    slugId = article.sarticleSlug.id
    slugParentId = article.sarticleSlug.parentId
    slug = article.sarticleSlug.slug
  }

  let sseoItem = article.sseoItem
  let seo = { title: '', keywords: '', description: '' }
  if (sseoItem && sseoItem.id) {
    seo = {
      title: sseoItem.title,
      keywords: sseoItem.keywords,
      description: sseoItem.description
    }
  }

  let fileListInfo = article.fileList
  let fileList = []
  if (fileListInfo && fileListInfo.length > 0) {
    fileList = fileListInfo.map(item => {
      return {
        id: item.hrepertory.id,
        originalFilename: item.hrepertory.originalFilename,
        suffix: item.hrepertory.suffix
      }
    })
  }

  let sarticle = article.sarticle
  return {
    // 图片列表
    imageList: imageList,
    id: sarticle.id,
    categoryId: categoryId,
    systemId: sarticle.systemId,
    title: sarticle.title,
    author: sarticle.author,
    origin: sarticle.origin,
    viewCount: sarticle.viewCount,
    synopsis: sarticle.synopsis,
    rewrite: sarticle.rewrite,
    orderNum: sarticle.orderNum,
    isShow: sarticle.isShow,
    content: sarticle.content,
    releasedAt: sarticle.releasedAt,
    slugId: slugId,
    slugParentId: slugParentId,
    slug: slug,
    seo: seo,
    // 文件列表
    fileList: fileList,
    // 自定义链接
    customLink: article.customLink
  }
}
// 提交数据时的产品文件信息数据
// function requestArticleFileParam (article) {
//   let files = article.fileList.map(item => {
//     return {
//       id: item.id
//     }
//   })
//   return files
// }
</script>

<style scoped lang="scss">
.system-content-item {
  padding-bottom: 60px;
  .header {
    min-height: 36px;
    .border {
      width: 100%;
      height: 1px;
      border-bottom: 2px solid #e5e5e5;
      margin-top: 12px;
      margin-bottom: 24px;
    }
  }
  .el-form-item {
    margin-bottom: 15px;
  }
  .width-limit {
    min-width: 180px;
    max-width: 640px;
  }
}
.footfixed {
  position: fixed;
  z-index: 1000;
  bottom: 0;
  left: 220px;
  right: 0;
  background: #fff;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  margin-bottom: 0 !important;
  text-align: right;
}
.changHgh /deep/ .el-input__inner {
  line-height: 1.3;
  padding-top: 4px;
  padding-bottom: 4px;
}
</style>
